package com.wtp.wallpaper.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wtp.wallpaper.common.constant.JwtClaimsConstant;
import com.wtp.wallpaper.common.constant.PictureTypeConstant;
import com.wtp.wallpaper.common.context.BaseContext;
import com.wtp.wallpaper.mapper.UserMapper;
import com.wtp.wallpaper.pojo.entity.Collect;
import com.wtp.wallpaper.pojo.entity.Picture;
import com.wtp.wallpaper.pojo.entity.Score;
import com.wtp.wallpaper.pojo.entity.User;
import com.wtp.wallpaper.pojo.query.PageQuery;
import com.wtp.wallpaper.pojo.vo.PictureVO;
import com.wtp.wallpaper.pojo.vo.UserVO;
import com.wtp.wallpaper.common.properties.JwtProperties;
import com.wtp.wallpaper.service.CollectService;
import com.wtp.wallpaper.service.PictureService;
import com.wtp.wallpaper.service.ScoreService;
import com.wtp.wallpaper.service.UserService;
import com.wtp.wallpaper.utils.JwtUtil;
import com.wtp.wallpaper.utils.PojoConvertUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService{

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private CollectService collectService;

    @Autowired
    private ScoreService scoreService;

    @Autowired
    private PictureService pictureService;
    @Override
    public UserVO login(User user) {

        User one = lambdaQuery()
                .eq(User::getPhone, user.getPhone())
                .one();

        log.info("user:{}",user);
        UserVO userVO = new UserVO();
        Map<Long,Float> userScore = new HashMap<>();
        Set<Long> userCollect = new HashSet<>();
        if(one == null){
            user.setNickname(nickNameHandle(user.getPhone()));
            user.setPassword(DigestUtil.md5Hex("123456"));
            user.setCoin(3);
            save(user);
            log.info("userid:{}", user.getId());
            BeanUtil.copyProperties(user,userVO);

        }else{
            BeanUtil.copyProperties(one,userVO);

            //获取该用户的评分 映射为map给前端提供用户评分
            List<Score> scoreList = scoreService.getScoreListByUserId(one.getId());
            scoreList.forEach((score -> {
                userScore.put(score.getPicId(),score.getScore());
            }));

            //获取用户的收藏，映射为set提供给前端验证
            List<Collect> collectList = collectService.getCollectListByUserId(one.getId());
            collectList.forEach(collect -> userCollect.add(collect.getPicId()));
        }
        //设置该用户的userScore 和userCollect
        userVO.setUserScores(userScore);
        userVO.setUserCollects(userCollect);

        Map<String,Object> map = new HashMap<>();
        map.put(JwtClaimsConstant.USER_ID,userVO.getId());
        map.put(JwtClaimsConstant.PHONE,userVO.getPhone());
        map.put(JwtClaimsConstant.NICKNAME,userVO.getNickname());

        String jwt = JwtUtil.createJWT(jwtProperties.getAdminSecretKey(), jwtProperties.getAdminTtl(), map);
        userVO.setToken(jwt);
        log.info("UserVO:{}",userVO);
        return userVO;
    }

    public UserVO getUserInfo(String id) {

        return BeanUtil.copyProperties(getById(id),UserVO.class);
    }

    @Override
    public List<PictureVO> getUserWallByType(PageQuery pageQuery, String type) {

        List<Long> pictureId;
        if(type.equals(PictureTypeConstant.COLLECT)){
            pictureId = collectService.getPictureIdsByUserId(Long.valueOf(BaseContext.getCurrentId()));
        }else if(type.equals(PictureTypeConstant.SCORE)){
            pictureId = scoreService.getPictureIdsByUserId(Long.valueOf(BaseContext.getCurrentId()));
        } else {
            pictureId = new ArrayList<>();
        }

        if(pictureId.isEmpty()){
            return List.of();
        }
        Page<Picture> list = pictureService.getPageListByPictureIds(pageQuery.toMpPage(),pictureId);

        List<Picture> records = list.getRecords();
        records.sort(Comparator.comparing(p -> pictureId.indexOf(p.getId())));
        return PojoConvertUtil.convert(records,PictureVO.class);
    }

    private String nickNameHandle(String phone){
        return phone.substring(0,3) + "****" + phone.substring(7);
    }

}
